package info.empathymobile.monitor;

import info.empathymobile.monitor.business.DatabaseHelper;
import info.empathymobile.monitor.business.OrmLiteBase;
import info.empathymobile.monitor.business.beans.MonitorEntry;
import info.empathymobile.monitor.receivers.BatteryReceiver;
import info.empathymobile.monitor.receivers.ConnectivityReceiver;
import info.empathymobile.monitor.receivers.ShutdownReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.IBinder;

import com.j256.ormlite.android.apptools.OrmLiteBaseService;

public class EmpathyMonitorService extends OrmLiteBaseService<DatabaseHelper> implements OrmLiteBase<DatabaseHelper> {

	private BatteryReceiver batteryReceiver = new BatteryReceiver();
	private ConnectivityReceiver connectivityReceiver = new ConnectivityReceiver();
	private ShutdownReceiver shutdownReceiver = new ShutdownReceiver();
	private boolean receiversRegistered = false;

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		registerMonitorReceivers();
		if(isToDoTheBootScan()){
			doTheBootScan();
		}
		return START_STICKY;
	}
	
	private boolean isToDoTheBootScan() {
		SharedPreferences sharedPref = getSharedPreferences(EmpathyMonitorController.EMPATHY_MONITOR_SHARED_PREFERENCES, Context.MODE_MULTI_PROCESS);
		return sharedPref.getBoolean(EmpathyMonitorController.DO_THE_BOOT_SCAN_PREFERENCE, false);
	}

	private void doTheBootScan() {
		new EmpathyMonitorController(this).initAsyncEmpathyMonitorScan(MonitorEntry.OS_ENTRY_LOG_CLASS, MonitorEntry.OS_ENTRY_BOOT);
	}

	private void registerMonitorReceivers() {
		IntentFilter batteryReceiverIntentFilter = new IntentFilter();
		batteryReceiverIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
		batteryReceiverIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
		this.registerReceiver(batteryReceiver, batteryReceiverIntentFilter);
		
		this.registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
		
		IntentFilter shutdownReceiverIntentFilter = new IntentFilter();
		shutdownReceiverIntentFilter.addAction(Intent.ACTION_SHUTDOWN);
		shutdownReceiverIntentFilter.addAction(Intent.ACTION_REBOOT);
		shutdownReceiverIntentFilter.addAction("android.intent.action.QUICKBOOT_POWEROFF");
		this.registerReceiver(shutdownReceiver, shutdownReceiverIntentFilter);
		
		receiversRegistered = true;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		if(receiversRegistered){
			this.unregisterReceiver(batteryReceiver);
			this.unregisterReceiver(connectivityReceiver);
			this.unregisterReceiver(shutdownReceiver);
		}
	}
}
